package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.dto.ArticleDto;
import com.heima.article.dto.ArticleHomeDto;
import com.heima.article.dto.ArticleInfoDto;
import com.heima.article.dto.BehaviorDto;
import com.heima.article.dto.*;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.entity.ApCollection;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.entity.ArticleInfoBehavior;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.util.AppThreadLocalUtil;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-04-13
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {


    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    @Lazy
    private IAsyncService asyncService;

    @Override
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(dto, article);
        // 判断是否存在id
        if (dto.getId() == null) {
            // 不存在id
            // 新增文章表
            article.setCreatedTime(new Date());
            this.save(article);
            // 新增内容表
            ApArticleContent content = new ApArticleContent();
            content.setArticleId(article.getId());
            content.setContent(dto.getContent());
            contentService.save(content);

            // 生成静态页 异步线程
            System.out.println(Thread.currentThread().getName() + " 开始调用异步静态页服务...");
            asyncService.createHtml(article, dto.getContent());
            return ResponseResult.okResult(article.getId());
        }
        // 存在id
        // 更新文章表
        // 更新内容表
        this.updateById(article);
        LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
        // update ap_article_content set content = ? where article_id = ?
        update.eq(ApArticleContent::getArticleId, dto.getId());
        update.set(ApArticleContent::getContent, dto.getContent());
        contentService.update(update);
        return ResponseResult.okResult(dto.getId());
    }

    /**
     * 加载文章
     *
     * @param dto
     * @param type 0:最新  1: 更多
     * @return
     */
    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
        // 构建查询条件
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        // 判断频道id是否为0
        if (dto.getChannelId() != null && dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        // 判断操作类型 上拉  加载更多文章  查询比前端传递的最小发布时间更早的文章
        if (type == 1) {
            query.lt(ApArticle::getPublishTime, dto.getMinTime());
        } else {
            // 下拉  加载最新文章 查询比前端传递的最大发布时间更晚的文章
            query.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        // 过滤已下架\已删除文章
        query.eq(ApArticle::getIsDelete, false);
        query.eq(ApArticle::getIsDown, false);
        // 文章按照发布时间倒序排
        query.orderByDesc(ApArticle::getPublishTime);
        // 查询文章列表
        IPage<ApArticle> page = new Page<>(1, dto.getSize());
        IPage<ApArticle> iPage = this.page(page, query);
        return ResponseResult.okResult(iPage.getRecords());
    }

    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        // 查询文章表
        ApArticle article = this.getById(dto.getArticleId());
        // 查询内容表
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId, dto.getArticleId());
        ApArticleContent content = contentService.getOne(query);
        // 返回定义的格式
        Map<String, Object> map = new HashMap<>();
        map.put("config", article);
        map.put("content", content);
        return ResponseResult.okResult(map);
    }

    @Autowired
    private IApAuthorService apAuthorService;

    @Autowired
    private BehaviorFeign behaviorFeign;
    @Autowired
    private IApCollectionService apCollectionService;
    /**
     * 查询标记：喜欢 不喜欢 收藏 关注
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        //获取线程内用户
        User user = AppThreadLocalUtil.get();
        //查询文章的userId
        ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
        //参数中设置关注用户id
        dto.setFollowId(apAuthor.getUserId());
        //当前用户id
        dto.setUserId(user.getUserId());
        //feign远程调用查询
        ResponseResult<BehaviorDto> result = behaviorFeign.loadArticleBehavior(dto);
        LambdaQueryWrapper<ApCollection> query=new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId,dto.getArticleId());
        query.eq(ApCollection::getEntryId,user.getUserId());
        ApCollection one = apCollectionService.getOne(query);
        if(one!=null){
            BehaviorDto data = result.getData();
            data.setIscollection(true);
            result.setData(data);
        }
        return result;
    }


    @Override
    public ResponseResult loadArticleBehavior(ArticleDataDto dto) {
        Integer userId = AppThreadLocalUtil.get().getUserId();

        //todo 以后再说
        ArticleInfoBehavior infoBehavior = new ArticleInfoBehavior();
        if (userId != null && userId != 0) {
            dto.setUserId(userId);
            UnlikesBehaviorDto unlikesBehaviorDto = new UnlikesBehaviorDto();
            unlikesBehaviorDto.setType(1);
            ResponseResult<Integer> result = behaviorFeign.unlikesBehavior(unlikesBehaviorDto);
            Integer code = result.getCode();
            if (code.equals(AppHttpCodeEnum.SUCCESS.getCode())) {
                Integer data = result.getData();
                if (data != null) {
                    if (data == 1) {
                        infoBehavior.setIsunlike(false);

                    } else {
                        infoBehavior.setIsunlike(true);

                    }
                }
            }

        }
        return ResponseResult.okResult();
    }
}
